package com.youxue.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cangshi.permission.entity.CorrectJSONObject;
import com.cangshi.permission.entity.Token;
import com.cangshi.permission.entity.UserSubject;
import com.cangshi.permission.exception.LoginFailedException;
import com.youxue.entity.CorrectJsonObject;
import com.youxue.entity.ErrorJsonObject;
import com.youxue.entity.User;
import com.youxue.entity.UserEntity;
import com.youxue.permission.saver.SubjectHolder;
import com.youxue.service.UserService;
import com.youxue.util.emailCode.EmailManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * Created by 15c on 2018/1/16.
 */
@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 测试
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String test() {
        return JSONObject.toJSONString(userService.select(1));
    }

    /**
     * 邮箱注册
     * 获取验证码
     *
     * @param email 邮箱
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getVerificationCode", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String getVerificationCode(@RequestParam(required = false) String email) {
        if (null == email) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "缺少邮箱参数");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if ("".equals(email)) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102, "邮箱参数值为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //前端判断email格式以及不允许传空值
        //发送验证码到邮箱
        EmailManage emailManage = new EmailManage(email);
        emailManage.addEmail();
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("生成发送验证码成功");
        correctJsonObject.setData(0);
        return correctJsonObject.toString();
    }

    /**
     * 邮箱注册
     */
    @ResponseBody
    @RequestMapping(value = "/register/email", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String registerByemail(@RequestParam(required = false) String email,
                           @RequestParam(required = false) String password,
                           @RequestParam(required = false) String verificationCode) {
        if (null == email || null == password || null == verificationCode) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(109, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if ("".equals(email) || "".equals(password) || "".equals(verificationCode)) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(110, "参数值存在空值");
            return JSONObject.toJSONString(errorJsonObject);
        }
        User user = new User();
        user.setUserEmail(email);
        User resultUser = userService.showUserByEmail(email);
        if (null != resultUser) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(111, "该邮箱已经注册");
            return JSONObject.toJSONString(errorJsonObject);
        }

        //服务器保存的验证码
        String checkCode = null;
        //此处可能会出现空指针异常，在用户没获取验证码是会出现
        try {
            checkCode = EmailManage.getEmail(email).getMailCheckString();
        } catch (NullPointerException e) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(112, "用户未获取验证码");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (!verificationCode.equals(checkCode)) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(113, "验证码错误，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }


        user.setUserPassword(password);

        int result = userService.addUser(user);
        if (1 == result) {
            CorrectJSONObject correctJSONObject = new CorrectJSONObject("注册成功");

            return JSONObject.toJSONString(correctJSONObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(114, "注册失败，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }

    }


    /**
     * 电话号码注册
     */

    @ResponseBody
    @RequestMapping(value = "/register/phone", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String registerByphone(@RequestParam(required = false) String telnumber,
                           @RequestParam(required = false) String password,
                           @RequestParam(required = false) String verificationCode) {
        // 判断参数是否完整。
        if (telnumber == null || password == null) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(100, "用户名或密码参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 判断参事值是否为空。
        if (telnumber.equals("") || password.equals("")) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "用户名或密码为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        User telUser = new User();
        telUser.setUserTelphone(telnumber);
        User user = userService.selectUserIdByPhone(telUser);
        // 判断telPhone是否已经注册(通过查询TelPhone，看是否存在)
        if (user != null) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102, "电话号码已被注册");
            return JSONObject.toJSONString(errorJsonObject);
        }
        telUser.setUserPassword(password);
        int result = userService.addUser(telUser);
        //数据库插入成功返回1
        if (result == 1) {
            return new CorrectJSONObject("用户注册成功").toString();

        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(103, "注册失败");
            return JSONObject.toJSONString(errorJsonObject);
        }


    }

    /**
     * 用户登录（email、phone）
     *
     * @param username
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String login(@RequestParam(required = false) String username,
                 @RequestParam(required = false) String password) {
        // 判断参数是否完整。
        if (username == null || password == null) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(106, "用户名或密码参数不完整");
            return JSONObject.toJSONString(errorJsonObject);

        }
        if ("".equals(username) || "".equals(password)) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(107, "用户名或密码为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        String authorization = null;
        try {
            // 登录，并获取证书
            authorization = subject.login(new Token(username, password));
            CorrectJSONObject correctJSONObject = new CorrectJSONObject("登录成功");

            // 设置返回json
            correctJSONObject.setData(authorization);
            return correctJSONObject.toString();

        } catch (LoginFailedException e) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(108, "账号或密码错误,或者该账户已被冻结！");
            return JSONObject.toJSONString(errorJsonObject);
        }

    }

    /**
     * 用户部分信息展示
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/show", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String userInfoShow() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        User resultUser = userService.showUserPartInfo(userId);
        if (null == resultUser) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(115, " 查询信息失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("用户信息获取成功");
        correctJsonObject.setData(resultUser);

        return JSONObject.toJSONString(correctJsonObject);

    }

    /**
     * 用户基本信息修改
     *
     * @param user
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/details/revise", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String userReviseInfo(@RequestBody(required = false) User user) {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();

        //判断user参数是否为空
        if (null == user) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(104, "参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (null == user.getUserId()) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(107, "未指定欲修改用户Id");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (userId != user.getUserId()) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(106, "没有权限修改该用户信息");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int result = userService.updateUser(user);
        if (1 != result) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(205, "用户信息更新失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
        return new CorrectJSONObject("修改成功").toString();

    }


    /**
     * 用户忘记密码，通过邮箱重置
     */
    @ResponseBody
    @RequestMapping(value = "/resetPasswordByEmail", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String resetEmailPassword(@RequestParam(required = false) String email,
                              @RequestParam(required = false) String newpassword,
                              @RequestParam(required = false) String verificationCode) {
        if (null == email || null == newpassword || null == verificationCode) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(109, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if ("".equals(email) || "".equals(newpassword) || "".equals(verificationCode)) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(110, "参数值存在空值");
            return JSONObject.toJSONString(errorJsonObject);
        }

        //服务器保存的验证码
        String checkCode = null;
        //此处可能会出现空指针异常，在用户没获取验证码是会出现
        try {
            checkCode = EmailManage.getEmail(email).getMailCheckString();
        } catch (NullPointerException e) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(112, "用户未获取验证码");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (!verificationCode.equals(checkCode)) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(113, "验证码错误，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }
        User user = new User();
        user.setUserEmail(email);
        if (null == userService.selectUserIdByEmail(user)) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(115, "该用户还未注册!");
            return JSONObject.toJSONString(errorJsonObject);
        }
        user.setUserPassword(newpassword);
        int result = userService.resetPasswordByemail(user);
        if (1 == result) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("用户密码重置成功");

            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(114, "密码重置失败，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }

    }


    /**
     * 通过证书获取用户信息
     *
     * @return
     */


    @ResponseBody
    @RequestMapping(value = "/onedetails", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String userInfo() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        User resultUser = userService.showUserPartInfo(userId);
        if (null == resultUser) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(115, "查询信息失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("用户信息获取成功");
        correctJsonObject.setData(resultUser);

        return JSONObject.toJSONString(correctJsonObject);

    }

    @ResponseBody
    @RequestMapping(value = "/details/addBalance", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String addBalance(@RequestParam(required = false) Double money){
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        int result=userService.reviseBalanceByUserId(userId,money);
        if (result==1){
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("充值成功");
            return JSONObject.toJSONString(correctJsonObject);
        }else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(125, "充值失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 用户图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/details/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String imageUpload(HttpServletRequest request, @RequestBody(required = false) String image) {
        System.out.println("image为：" + image + " end");
        ErrorJsonObject errorJsonObject;
        //指定头类型
        String headerPng = "data:image/png;base64,";
        String headerJpG = "data:image/jpeg;base64,";

        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/img");

        System.out.println("realPath为：" + realPath + "  end");
        //声明图片地址
        String imgAddress = null;
        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------->" + extensionName);
        if (image != null && (image.indexOf(headerPng) != 0 || image.indexOf(headerJpG) != 0)) {
            String headPng = image.substring(0, headerPng.length());
            String headJpG = image.substring(0, headerJpG.length());
            if (headerJpG.equals(headJpG)) {
                //去掉头部
                image = image.substring(headerJpG.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else if (headerPng.equals(headPng)) {
                //去掉头部
                image = image.substring(headerPng.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else {
                errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
                return errorJsonObject.toJSONString();
            }
        } else {
            errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return errorJsonObject.toJSONString();
        }
    }


    /**
     * 用户图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String userImageUpload(HttpServletRequest request, @RequestBody String image) {

        //指定头类型
        String header = "data:image/png;base64,";


        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/img");

        //声明图片地址
        String imgAddress = null;

        //获取文件名
        //String originalFilename = image.getOriginalFilename();

        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------->" + extensionName);

        //判断文件格式是否正确
        if (image == null || image.indexOf(header) != 0) {

            //返回错误信息
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return JSONObject.toJSONString(errorJsonObject);

        } else {

            //去掉头部
            image = image.substring(header.length());

            BASE64Decoder decoder = new BASE64Decoder();

            try {
                if (!image.isEmpty()) {

                    //以当前时间加随机数命名上传文件
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                    String date = sdf.format(new java.util.Date());


                    //设置图片名为当前时间加随机数
                    imgAddress = date + new Random().nextInt() + extensionName;

                    //将文件上传到服务器
                    byte[] decodedBytes = decoder.decodeBuffer(image);

                    FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                    out.write(decodedBytes);

                    out.close();

                    //设置返回结果
                    CorrectJSONObject correctJSONObject = new CorrectJSONObject("上传成功");
                    correctJSONObject.setData(imgAddress);
                    return JSON.toJSONString(correctJSONObject);

                } else {
                    ErrorJsonObject errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在");
                    return JSONObject.toJSONString(errorJsonObject);



                }
            } catch (IOException e) {
                ErrorJsonObject errorJsonObject = new ErrorJsonObject(109, e.getMessage());
                return JSONObject.toJSONString(errorJsonObject);

            }
        }

    }

}
